var serverUrl = "https://www.skyhtkj.com";
var previewUrl = "https://www.skyhtkj.com/jxszy_static/";
var exceptionAddrArr = []

//轻提示
function showToast(title) {
  wx.showToast({
    title: title,
    icon: 'none',
    duration: 2000
  })
}

//重提示
function showModel(content, cb) {
  wx.showModal({
    title: '提示',
    content: content,
    showCancel: false,
    success(res) {
      if (res.confirm) {
        cb && cb()
      }
    }
  })
}

// 请求头处理函数
function CreateHeader(url, type) {
  let header = {}
  if (type == 'POST_PARAMS') {
    header = {
      'content-type': 'application/json'
    }
  } else {
    header = {
      'content-type': 'application/json;charset=UTF-8'
    }
  }
  if (exceptionAddrArr.indexOf(url) == -1) { //排除请求的地址不需要token的地址
    let token = wx.getStorageSync("token");
    header['Authorization'] = token;
  }
  return header;
}

//post请求，数据在body中
function postRequest(url, data) {
  wx.showNavigationBarLoading()
  let header = CreateHeader(url, 'POST');
  return new Promise((resolve, reject) => {
    wx.request({
      url: serverUrl + url,
      data: data,
      header: header,
      method: 'POST',
      success: (res => {
        if (res.statusCode === 200) {
          //200: 服务端业务处理正常结束
          let { code, object, message } = res.data
          if (code == 1) {
            resolve(object)
          } else if (code == 5) {
            showToast(message)
            wx.redirectTo({
              url: '/pages/login/login',
            })
          } else {
            showToast(message)
          }
        } else {
          showToast('网络失败')
          reject(res)
        }
        wx.hideNavigationBarLoading()
      }),
      fail: (res => {
        showModel('网络失败')
        wx.hideNavigationBarLoading()
        reject(res)
      })
    })
  })
}

//get 请求
function getRequest(url, data) {
  wx.showNavigationBarLoading()
  let header = CreateHeader(url, 'GET');
  return new Promise((resolve, reject) => {
    wx.request({
      url: serverUrl + url,
      data: data,
      header: header,
      method: 'GET',
      success: (res => {
        if (res.statusCode === 200) {
          //200: 服务端业务处理正常结束
          let { code, object, message } = res.data
          if (code == 1) {
            resolve(object)
          } else if (code == 5) {
            showToast(message)
            wx.redirectTo({
              url: '/pages/login/login',
            })
          } else {
            showToast(message)
          }
        } else {
          showToast('网络失败')
          reject(res)
        }
        wx.hideNavigationBarLoading()
      }),
      fail: (res => {
        showToast('网络失败')
        wx.hideNavigationBarLoading()
        reject(res)
      })
    })
  })
}

//文件上传
function uploadFile(url, filePath, data) {
  let header = CreateHeader(url, 'POST');
  return new Promise((resolve, reject) => {
    wx.uploadFile({
      filePath: filePath,
      header: header,
      name: 'file',
      formData: data || '',
      url: serverUrl + url,
      success: (res => {
        if (res.statusCode === 200) {
          //200: 服务端业务处理正常结束
          let { code, object, message } = JSON.parse(res.data)
          console.log(code, object, message)
          if (code == 1) {
            resolve(object)
          } else if (code == 5) {
            showToast(message)
            wx.redirectTo({
              url: '/pages/login/login',
            })
          } else {
            showToast(message)
          }
        } else {
          showToast('网络失败')
          reject(res)
        }
        wx.hideNavigationBarLoading()
      }),
      fail: (res => {
        showToast('网络失败')
        wx.hideNavigationBarLoading()
        reject(res)
      })
    })
  })
}

//文件下载
function outPut(url) {
  // 接口请求
  let token = ''
  let strogeToken = wx.getStorageSync('token')
  if (strogeToken) {
    token = `&token=${strogeToken}`
  }
  let header = CreateHeader(url, 'GET');
  wx.request({
    url: serverUrl + url + token,// 后端接口地址
    header: header,
    method: "GET",
    responseType: "arraybuffer", //此处是请求文件流，必须带入的属性
    success: rest => {
      if (rest.statusCode === 200) {
        const fs = wx.getFileSystemManager(); //获取全局唯一的文件管理器
        fs.writeFile({ // 写文件
          filePath: wx.env.USER_DATA_PATH + "/finance.html", // wx.env.USER_DATA_PATH 指定临时文件存入的路径，后面字符串自定义
          data: rest.data,
          encoding: "binary", //二进制流文件必须是 binary
          success(res) {
            wx.saveVideoToPhotosAlbum({ // 新开页面打开文档
              filePath: wx.env.USER_DATA_PATH + "/finance.html",  //拿上面存入的文件路径
              success: function (res) {

              }
            })
          }
        });
      }
    }
  })

}

//post请求，数据按照query方式传给后端
function postParamsRequest(url, data) {
  wx.showNavigationBarLoading()
  let header = CreateHeader(url, 'POST_PARAMS');
  let useurl = url;
  const keys = Object.keys(data)
  let params = '?'
  for (let i = 0; i < keys.length; i++) {
    const key = keys[i]
    let value = data[key]
    if (value != null && value != '') {
      if (i != 0) {
        params += '&'
      }
      //对特殊字符进行转义
      value = encodeURIComponent(value)
      params += key + '=' + value
    }

  }
  return new Promise((resolve, reject) => {
    wx.request({
      url: serverUrl + useurl + params,
      data: data,
      header: header,
      method: 'POST',
      success: (res => {
        if (res.statusCode === 200) {
          //200: 服务端业务处理正常结束
          let { code, object, message } = res.data
          if (code == 1) {
            resolve(object)
          } else if (code == 5) {
            showToast(message)
            wx.redirectTo({
              url: '/pages/login/login',
            })
          } else {
            showToast(message)
          }
        } else {
          wx.hideNavigationBarLoading()
          showToast('网络失败')
          reject(res)
        }
      }),
      fail: (res => {
        wx.hideNavigationBarLoading()
        showToast('网络失败')
        reject(res)
      })
    })
  })
}

//post请求url
function postRequestUrl(url, data) {
  wx.showNavigationBarLoading()
  let header = CreateHeader(url, 'POST');
  return new Promise((resolve, reject) => {
    wx.request({
      url: serverUrl + url + data,
      header: header,
      method: 'POST',
      success: (res => {
        if (res.statusCode === 200) {
          //200: 服务端业务处理正常结束
          let { code, object, message } = res.data
          if (code == 1) {
            resolve(object)
          } else if (code == 5) {
            showToast(message)
            wx.redirectTo({
              url: '/pages/login/login',
            })
          } else {
            showToast(message)
          }
        } else {
          showToast('网络失败')
          reject(res)
        }
        wx.hideNavigationBarLoading()
      }),
      fail: (res => {
        showModel('网络失败')
        wx.hideNavigationBarLoading()
        reject(res)
      })
    })
  })
}

module.exports.getRequest = getRequest;
module.exports.postRequest = postRequest;
module.exports.uploadFile = uploadFile;
module.exports.serverUrl = serverUrl;
module.exports.previewUrl = previewUrl;
module.exports.outPut = outPut;
module.exports.postParamsRequest = postParamsRequest;
module.exports.postRequestUrl = postRequestUrl;